import api, { extractData } from './axios';
import { Role } from '../types';

/**
 * 角色相关API
 * 对应后端RoleRouter.js中的路由
 */

/**
 * 获取角色列表
 * 对应后端GET /adminapi/roles路由
 * @returns 角色列表，包含MongoDB的所有字段
 */
export const getRoleList = async () => {
  try {
  const response = await api.get('/roles');
  return extractData<Role[]>(response);
  } catch (error) {
    console.error('获取角色列表失败:', error);
    // 返回空数组而不是抛出错误
    return [];
  }
};

/**
 * 根据ID获取角色
 * 对应后端GET /adminapi/roles/:id路由
 * @param id 角色ID，支持MongoDB的ObjectId
 * @returns 角色信息
 */
export const getRoleById = async (id: number | string) => {
  const response = await api.get(`/roles/${id}`);
  return extractData<Role>(response);
};

/**
 * 添加角色
 * 对应后端POST /adminapi/roles路由
 * @param data 角色数据，与MongoDB RoleModel对应
 * @returns 添加结果，包含MongoDB文档信息
 */
export const addRole = async (data: Partial<Role>) => {
  const response = await api.post('/roles', data);
  return extractData<Role>(response);
};

/**
 * 更新角色
 * 对应后端PUT /adminapi/roles/:id路由
 * @param id 角色ID，支持MongoDB的ObjectId
 * @param data 角色数据，与MongoDB RoleModel对应
 * @returns 更新结果，包含MongoDB文档信息
 */
export const updateRole = async (id: number | string, data: Partial<Role>) => {
  // 确保data中不包含id和_id字段，避免MongoDB文档ID冲突
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const { id: _, _id: __, ...updateData } = data;
  
  const response = await api.put(`/roles/${id}`, updateData);
  return extractData<Role>(response);
};

/**
 * 更新角色权限
 * 对应后端PATCH /adminapi/roles/:id/rights路由
 * @param id 角色ID，支持MongoDB的ObjectId
 * @param rights 权限ID列表，与MongoDB RoleModel的rights字段对应
 * @returns 更新结果，包含MongoDB文档信息
 */
export const updateRoleRights = async (id: number | string, rights: string[]) => {
  const response = await api.patch(`/roles/${id}/rights`, { rights });
  return extractData<Role>(response);
};

/**
 * 删除角色
 * 对应后端DELETE /adminapi/roles/:id路由
 * @param id 角色ID，支持MongoDB的ObjectId
 * @returns 删除操作的响应
 */
export const deleteRole = async (id: number | string) => {
  const response = await api.delete(`/roles/${id}`);
  return response.data;
};

/**
 * 检查权限
 * 对应后端POST /adminapi/permissions/check路由
 * @param permissionKey 权限键
 * @returns 是否有权限
 */
export const checkPermission = async (permissionKey: string) => {
  const response = await api.post('/permissions/check', { permissionKey });
  const result = extractData<{hasPermission: boolean}>(response);
  return result.hasPermission;
};

/**
 * 检查权限版本
 * 对应后端GET /adminapi/permissions/version-check路由
 * @param currentVersion 当前权限版本
 * @returns 权限版本信息
 */
export const checkPermissionVersion = async (currentVersion: string) => {
  const response = await api.get('/permissions/version-check', {
    params: { currentVersion }
  });
  return extractData<{
    version: string;
    needsUpdate: boolean;
  }>(response);
};

export default {
  getRoleList,
  getRoleById,
  addRole,
  updateRole,
  updateRoleRights,
  deleteRole,
  checkPermission,
  checkPermissionVersion
}; 